<?php

namespace Home\Controller;

use Think\Controller;
//use Imp\api_demo;
use \Imp\api_demo\SmsDemo;

//use \Model\MyInformationModel;
use \Model\UserModel;//用户模型   
use \Model\TempUserModel;//临时用户模型

//公共类
use \Common\Common\Decrypt;//公共加密类
use Common\Common\UserGlobal;  //公共类
use \Home\Common\Aes;

class UserController extends CommonController
{



    //个人中心
	public function my_center()
	{
		dump($_SESSION['user_account']);
		//判断用户是否登录，若已经登录则，展示用户个人中心，若没登录，则展示用户登录界面
		if (!(UserGlobal::check_user_state() == 1)) {
			$this->redirect('User/login');
		} else {
			$this->display();
		}
	}

    //用户登录
	public function user_login()
	{
		$token = $_POST['token'];
		$user_account = $_POST['user_account'];	//获取账号
		$user_password = $_POST['user_password'];	//获取密码（MD5加密后的）

		//检测用户token
		if (!$this->check_token($token)) {
			echo '{"msg":"无效的请求"}';
			return;
		}

		$sql = array(
			'user_account' => $user_account,
			'user_password' => $user_password,
		);

		$info = D('user')->where($sql)->find();//检验用户账号密码
		if ($info) {
			$_SESSION['user_account'] = $user_account;		//设置用户session
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"用户名或密码错误"}';
		}
	}

    //短信登录
	public function msg_login()
	{
		// 两个逻辑：展示、收集
		$user_account = $_POST['user_account'];
		// dump($user_account);
		if ($user_account) {
	    //验证手机号
			$sql = array(
				'temp_user_account' => $user_account,
				'temp_user_authcode' => $_POST['authcode'],
			);
	    // dump($sql['temp_user_account']);
	    // dump($sql['temp_user_authcode']);

	    // dump("sql3:" . $sql['temp_user_account']);
			$info = D('temp_user')->where($sql)->find();
	    // dump($info);
			if ($info) {
		// $success_toURL = UserGlobal::get_user_currentURL;
				$success_toURL = "www.baidu.com";
				echo '{"data":"success", "success_toURL":"' . $success_toURL . '"}';
		//登录成功后设置cookies
				setcookie("user", $user_account, time() + 3600);
		// $this->redirect('Index/index');
			} else {
		// dump($info);
				echo '{"data":"账号或验证码有误！"}';
			}
			exit();
		}
		$this->display();
	}

    //获取验证码
	public function get_authcode()
	{

		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);

		$user_tel = $_POST['user_tel'];

		//实例化短信发送类
		$send = new SmsDemo;

		// 产生6位随机数
		$authCode = rand(100000, 999999);

		//向用户发送验证码
		if ($this->open_send_authcode) {
			$send->sendSms($user_tel, $authCode);   //若不想发送短信，请注释本行代码
		}

		echo '{"msg":"ok"}';
		//将用户的手机号保存在"临时用户"数据库中
		//判断临时数据库中是否有用户，如果已经存在，则修改用户的验证码，否则添加用户验证码
		$sql = array(
			'temp_user_tel' => $user_tel,
		);

		$db = D('temp_user');
		$info = $db->where($sql)->find();

		if ($info) { //如果临时表里有该用户，则更新新的验证码
			$db->temp_user_authcode = $authCode;
			$db->temp_user_authcode_time = date('y-m-d H:i:s', time());
			$db->save();
		} else { //否则添加新的验证码
			$sql2 = array(
				'temp_user_tel' => $temp_user_tel,
				'temp_user_authcode_time' => date('y-m-d H:i:s', time()),
				'temp_user_authcode' => $authCode,
			);
			$info = $db->add($sql2);
		}
	}

    //用户注册
	public function register()
	{
	
		// dump(md5("4"));
		// dump(substr(md5("4"), -10));
		
		// 两个逻辑：展示、收集
		// 获取用户输入数据
		$user_account = $_POST['user_account'];
		$auth_code = $_POST['auth_code'];

		if ($_POST) {
	    // dump($_POST);
	    // exit;
	    // 创建用户模型类
			$usermodel = new UserModel();
	    //设置用户默认信息
			$_POST['user_tel'] = $user_account;
			$_POST['user_nickname'] = "wysx_@" . substr(md5($user_account), -6);
			$_POST['user_head_img'] = "default/default_head_img.jpg";
			$_POST['user_head_small_img'] = "default/default_small_head_img.jpg";
	    //验证表单信息
			if (!$usermodel->create()) {
		// 如果创建失败 表示验证没有通过 输出错误提示信息
				exit($usermodel->getError());
			}
	    // exit;
	    //创建临时用户模型类
			$tempusermodel = new TempUserModel();
	    //检验验证码是否正确
			$info = $tempusermodel->checkAuthCode($user_account, $auth_code);
	    // dump($info);exit;
			if ($info) {
		//注册成功，数据库插入用户
				$usermodel->add();
				echo '{"data":"success"}';
		// echo "注册成功，请设置密码";
		//登录成功后设置cookies
				setcookie("user", $user_account, time() + 60);
		//设置session
				session_start();
				$_SESSION['user_account'] = $user_account;
		// echo "session:" . $_SESSION['user_account'];
		// exit;
		// $this->redirect('User/set_password');
			} else {
		// dump($info);
				echo '{"data":"验证码无效"}';
			}
		} else {
			$this->display();
		}

	}

    //设置密码
	public function set_password()
	{
		//两个逻辑：展示、收集

		$user_account = $_SESSION['user_account'];
		if (!$user_account) {
			$this->redirect('user/login');
		}

		if ($_POST) {
			//POST表单数据解密
			$dec = new Decrypt;
			$post = $dec->decrypt($_POST);
			$json_post = json_decode($post);	//转换成json对象 
		    // var_dump($json_post->data);
			//获取解密之后的密码
			$password1 = $json_post->data->password1;
			$password2 = $json_post->data->password2;
		    // echo $password1;	    echo $password2;exit;
			//密码检测
			$usermodel = new UserModel();
			if (!$usermodel->check_password($password1, $password2)) {
				exit;
			}
		    // $data['user_account'] = $user_account;
			$data['user_password'] = md5($password1);
		    // echo $user_account;	    echo $password1;
			$condition = 'user_account="' . $user_account . '"';
		    // echo $condition;
		    // dump($data);
			if ($usermodel->where($condition)->save($data)) {

				$success_toURL = "http://172.16.148.41/wysx/website/index.php/Index/index";
				echo '{"data":"success", "success_toURL":"' . $success_toURL . '"}';
				
				
				// echo '{"data":"success"}';
			} else {
				echo '{"data":"密码设置失败"}';
			}

		} else {
			$this->display();
		}
	}

    //退出登录状态
	function logout()
	{
		session_destroy();
		$this->redirect('Index/index');
	}


	//获取用户信息
	public function get_user_information()
	{
		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);
		$user_id = $_POST['user_id'];

		$usermodel = new UserModel();
		$info = $usermodel->model_get_user_information($user_id);
		echo json_encode($info);

	}
	




	//实名认证，post传入姓名和身份证号
	public function user_id_auth()
	{
		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);

		$user_id = $_POST['user_id'];		//用户id
		$realName = $_POST['user_name'];	//用户真实姓名
		$cardNo = $_POST['user_card_no'];	//用户身份证号

		//接口地址
		$url = 'http://idcardpro.market.alicloudapi.com/idcard';
		//appcode查看地址 https://market.console.aliyun.com/imageconsole/
		$appCode = 'febb800d53a144b4b1ff20dfe3f95a8f';
		$params['realName'] = $realName;
		$params['cardNo'] = $cardNo;
		//发送远程请求;
		$result = $this->DUOCAICREDIT($url, $params, $appCode, "POST");
		// var_dump("<pre>");
		// echo json_encode($result);
		//返回结果
		if ($result['error_code'] == 0) {
			// echo $result['reason']; //信息一致
			//数据库操作，修改用户认证状态
			$user_sex = $result['result']['details']['sex'];		//提取返回值里面的性别
			$usermodel = new UserModel();
			$usermodel->user_realname_auth($user_id, $realName, $cardNo, $user_sex);

			echo '{"msg":"ok"}';
		} else {
			// echo $result['reason'];  //信息不一致
			echo '{"msg":"error","code":"1001"}';
		}
	}

	//检测用户信息是否正确
	public function check_user_auth($user_id, $realName, $cardNo, $token)
	{
		$len = preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $realName);
		// echo $realName;
		// echo $len;
		if (!$len) {
			// echo "1";
			return false;
		}

		if (!is_numeric($cardNo) || strlen($cardNo) != 18) {	//身份证格式有误
			// echo "2";
			return false;
		}

		//如果token有误

		if (!$this->check_token($token)) {
			return false;
		}

		return true;
	}


	/**
	 * DUOCAICREDIT 获取数据
	 * @param $url 请求地址
	 * @param array $params 请求的数据
	 * @param $appCode 您的APPCODE
	 * @param $method
	 * @return array|mixed
	 */
	function DUOCAICREDIT($url, $params = array(), $appCode, $method = "GET")
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $method == "POST" ? $url : $url . '?' . http_build_query($params));
		curl_setopt($curl, CURLOPT_HTTPHEADER, array(
			'Authorization:APPCODE ' . $appCode
		));
		//如果是https协议
		if (stripos($url, "https://") !== false) {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
			//CURL_SSLVERSION_TLSv1
			curl_setopt($curl, CURLOPT_SSLVERSION, 1);
		}
		//超时时间
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
		curl_setopt($curl, CURLOPT_TIMEOUT, 60);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//通过POST方式提交
		if ($method == "POST") {
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
		}
		//返回内容
		$callbcak = curl_exec($curl);
		//http status
		$CURLINFO_HTTP_CODE = curl_getinfo($curl, CURLINFO_HTTP_CODE);
		//关闭,释放资源
		curl_close($curl);
		//如果返回的不是200,请参阅错误码 https://help.aliyun.com/document_detail/43906.html
		if ($CURLINFO_HTTP_CODE == 200)
			return json_decode($callbcak, true);
		else if ($CURLINFO_HTTP_CODE == 403)
			return array("error_code" => $CURLINFO_HTTP_CODE, "reason" => "e1001");//剩余次数不足
		else if ($CURLINFO_HTTP_CODE == 400)
			return array("error_code" => $CURLINFO_HTTP_CODE, "reason" => "e1002");//APPCODE错误
		else
			return array("error_code" => $CURLINFO_HTTP_CODE, "reason" => "e1002");//APPCODE错误
	}




	//绑定用户微信号
	//post参数：用户id,用户微信,请求token
	public function update_user_wechat()
	{

		//检测用户token，token有误则直接终止
		// $this->check_token($_POST['token']);

		$user_id = $_POST['user_id'];
		$user_wechat = $_POST['user_wechat'];

		if (strlen($user_wechat) > 20) {
			echo '{"msg":"微信号格式有误"}';
			return;
		}

		//数据库更新
		$usermodel = new UserModel();
		if ($usermodel->model_update_user_wechat($user_id, $user_wechat)) {
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"操作失败！"}';
		}
	}


	//修改用户昵称
	//post参数：用户id,用户新昵称,请求token
	public function update_user_nickname()
	{

		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);

		$user_id = $_POST['user_id'];
		$user_new_nickname = $_POST['user_new_nickname'];


		if (strlen($user_new_nickname) > 12) {
			echo '{"msg":"error","code":"1002"}';	//错误代码1002，格式有误
			return;
		}

		//数据库更新
		$usermodel = new UserModel();
		if ($usermodel->model_update_user_nickname($user_id, $user_new_nickname)) {
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"操作失败！"}';
		}
	}


	//修改用户联系方式
	public function update_user_contact_way()
	{
		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);

		$user_id = $_POST['user_id'];			//用户id
		$user_wechat = $_POST['user_wechat'];	//用户微信账号
		$user_tel = $_POST['user_tel'];			//用户手机号
		$user_qq = $_POST['user_qq'];			//用户qq号
		$user_default_contact_way = $_POST['user_default_contact_way'];			//用户qq号

		// 检验手机号
		if (!preg_match("/^1[345789]\d{9}$/", $user_tel)) {
			echo '{"msg":"手机号格式有误！"}';
			return;
		}

		// 检验微信号
		if (!preg_match("/^[a-z_\d]+$/", $user_wechat)) {
			echo '{"msg":"微信格式有误！"}';
			return;
		}

		//检验QQ号
		if (!preg_match("/^\d{6,12}$/", $user_qq)) {
			echo '{"msg":"QQ号格式有误！"}';
			return;
		}


		//数据库更新
		$usermodel = new UserModel();
		if ($usermodel->model_update_user_contact_way($user_id, $user_tel, $user_wechat, $user_qq, $user_default_contact_way)) {
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"操作失败！"}';
		}
	}

	//修改用户默认联系方式
	public function update_user_default_contact_way()
	{
		//检测用户token，token有误则直接终止
		// $this->check_token($_POST['token']);
		
		$user_id = $_POST['user_id'];
		$user_default_contact_way = $_POST['user_default_contact_way'];
		//数据库更新
		$usermodel = new UserModel();
		if ($usermodel->model_update_user_default_contact_way($user_id, $user_default_contact_way)) {
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"操作失败！"}';
		}


	}



	//修改用户密码
	public function update_user_password()
	{
		//检测用户token，token有误则直接终止
		$this->check_token($_POST['token']);

		$user_id = $_POST['user_id'];				 //用户id
		$user_password = $_POST['user_new_password'];//用户新密码

		//数据库更新
		$usermodel = new UserModel();
		if ($usermodel->model_update_user_password($user_id, $user_password)) {
			echo '{"msg":"ok"}';
		} else {
			echo '{"msg":"操作失败！"}';
		}
	}

	public function test()
	{
		$usermodel = new UserModel();
		$user_id = 1;
		$number = 100;
		$usermodel->wallet_increase($user_id, $number);
	}





}
